<template>
  <div>
    <div class="topBtn">
      <span v-for="item in warehouseData" :key="item.warehouseId">
        <a-button
          type="primary"
          :style="
            item.warehouseId === warehouseKey
              ? 'background: #3eae7c; color: #ffff; border: none'
              : 'background: #fff; color: #3eae7c; border: 1px solid #3eae7c'
          "
          style="margin-bottom: 10px"
          @click="searchWarehouse(item)"
        >
          {{ item.titleName }}
        </a-button>
      </span>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <div class="content">
        <div style="width: 30%">
          <div class="left-tree">
            <p>
              <a-button @click="addOneTree">添加一级菜单</a-button>
            </p>
            <a-input-search
              style="margin-bottom: 8px; width: 200px"
              placeholder="搜索"
              @change="onChange"
            />
            <a-tree
              :expandedKeys="expandedKeys"
              :autoExpandParent="autoExpandParent"
              :tree-data="treeData"
              @expand="onExpand"
              :replaceFields="{
                children: 'children',
                title: 'title',
                key: 'title',
              }"
            >
              <template slot="title" slot-scope="item">
                <p class="tree" @click="(e) => rowData(e, item)">
                  <span>
                    <span
                      v-if="
                        item.title.indexOf(searchValue) > -1 &&
                        !item.dataRef.isEdit
                      "
                    >
                      {{
                        item.title.substr(0, item.title.indexOf(searchValue))
                      }}
                      <span style="color: #f50">{{ searchValue }}</span>
                      {{
                        item.title.substr(
                          item.title.indexOf(searchValue) + searchValue.length
                        )
                      }}
                    </span>
                    <span>
                      <span
                        v-if="
                          !item.dataRef.isEdit &&
                          item.title.indexOf(searchValue) == -1
                        "
                        >{{ item.title }}</span
                      >
                      <a-input
                      :maxLength="128"
                        v-if="item.dataRef.isEdit"
                        style="width: 130px; height: 25px"
                        v-model="zanshiData"
                        @click.stop
                    /></span>
                  </span>
                  <span class="treeBtn">
                    <a-icon
                      v-if="item.sort != 2"
                      @click.stop="threeDataisEdit(item, 'add')"
                      type="plus"
                      style="cursor: pointer; margin-right: 10px"
                    />
                    <a-icon
                      v-if="!item.dataRef.isEdit"
                      type="edit"
                      style="cursor: pointer"
                      @click.stop="threeDataisEdit(item, 'edit')"
                    />
                    <a-icon
                      v-else
                      type="check-circle"
                      style="cursor: pointer; margin-right: 10px"
                      @click.stop="threeDataisEdit(item, 'sava')"
                    />

                    <a-icon
                      v-if="item.dataRef.isEdit"
                      type="close-circle"
                      style="cursor: pointer"
                      @click.stop="threeDataisEdit(item, 'close')"
                    />
                    <a-icon
                      type="delete"
                      class="iconBtn"
                      style="margin: 0 15px; cursor: pointer"
                      @click.stop="threeDataisEdit(item, 'del')"
                    />
                  </span>
                </p>
              </template>
            </a-tree>
          </div>
        </div>
        <div>
          <a-card :title="cardTitle">
            <a-card-grid
              style="width: 20%; height: 150px; text-align: center"
              v-for="item in rightData"
              :key="item.key"
            >
              {{ item.titleName }}
            </a-card-grid>
          </a-card>
        </div>
      </div>
    </a-spin>
    <a-modal
      v-model="visible"
      :title="modalTitle"
      @ok="handleOk"
      okText="添加"
      cancelText="取消"
    >
      <p>添加区域名：<a-input v-model.trim="titleName" /></p>
      <p>请输入排名：<a-input v-model="sortNo" /></p>
    </a-modal>
  </div>
</template>

<script>
import {
  warehouse_select,
  warehouse_add,
  warehouse_update,
  warehouse_delete,
  warehouse_chenkHouse,
} from "@/apis/system/WM/LocationManage";
import { warehouse } from "@/apis/common";
export default {
  created() {
    this.getWarehouseList();
    this.getWarehouseTree();
  },
  data() {
    return {
      CheckData: [],
      rightFlag: true,
      leftFlag: true,
      rightData: [],
      cardTitle: "",
      modalTitle: "添加一级库位",
      // 区域名
      titleName: "",
      // 仓库KEY
      threeDataisEditKey: null,
      warehouseKey: null,
      dataList: [],
      // 库位树的数据
      treeData: [],
      //仓库列表
      warehouseData: [],
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      visible: false,
      sortNo: "",
      sort: 0,
      addOneFlag: true,
      spinning: false,
      zanshiData: "",
      warehousePName: null,
    };
  },
  methods: {
    //每一行点击操作
    rowData(e, rowData) {
      this.addOneFlag = false;
      this.link = e.target;
      this.rowKey = rowData.warehouseId;
      this.cardTitle = rowData.title;
      this.rightData = [];
      this.CheckData = [];
      this.getRightArr(this.treeData);
    },
    getRightArr(data1) {
      let data = JSON.parse(JSON.stringify(data1));
      data.forEach((item) => {
        if (this.rowKey === item.warehousePid) {
          this.rightData.push(item);
          this.CheckData.push(item);
        }
        if (item.children && item.children.length >= 1) {
          this.getRightArr(item.children);
        }
      });
    },
    //树形操作
    async threeDataisEdit(rowData, flag) {
      let _this = this;
      if (flag === "add") {
        this.modalTitle = `为${rowData.title}添加区域`;
        this.threeDataisEditKey = rowData.warehouseId;
        this.warehousePName = rowData.titleName;
        this.rowKey = rowData.warehouseId;
        this.rightData = [];
        this.CheckData = [];
        this.getRightArr(this.treeData);
        this.leftFlag = true;
        this.visible = true;
      } else if (flag === "edit") {
        this.zanshiData = JSON.parse(JSON.stringify(rowData.title));
        this.leftFlag = false;
        let { code } = await warehouse_chenkHouse(rowData.warehouseId);
        if (code === "2091") {
          return false;
        }
        rowData.dataRef.isEdit = true;
      } else if (flag === "sava") {
        this.rightFlag = true;
        if (!this.leftFlag) {
          if (this.treeData.length >= 1) {
            this.treeData.forEach((item) => {
              if (item.warehouseId != rowData.warehouseId) {
                if (item.title === rowData.title) {
                  this.rightFlag = false;
                }
              }
            });
          } else {
            this.rightFlag = true;
          }
        } else {
          if (this.CheckData.length >= 1) {
            this.CheckData.forEach((item) => {
              if (item.titleName === rowData.titleName) {
                this.rightFlag = false;
              }
            });
          } else {
            this.rightFlag = true;
          }
        }
        if (this.rightFlag) {
          this.spinning = true;
          let { code } = await warehouse_update({
            key: rowData.warehouseId,
            titleName: this.zanshiData,
            revision: rowData.revision,
            warehouseId: rowData.warehouseId,
          });
          if (code === "10000") {
            this.getWarehouseTree();
            setTimeout(() => {
              rowData.dataRef.isEdit = false;
              this.spinning = false;
              this.zanshiData = "";
            }, 500);
          }
        } else {
          this.$message.error("同级目录不能重复区域名！");
        }
      } else if (flag === "close") {
        rowData.dataRef.isEdit = false;
        rowData.dataRef.title = this.zanshiData;
      } else if (flag === "del") {
        let { code } = await warehouse_chenkHouse(rowData.warehouseId);
        if (code === "2091") {
          return false;
        }
        this.$confirm({
          title: `你确定删除${rowData.title}吗?`,
          okText: "确认",
          cancelText: "取消",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await warehouse_delete({
                  warehouseId: rowData.warehouseId,
                  revision: rowData.revision,
                  key: rowData.warehouseId,
                });
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              _this.getWarehouseTree(_this.warehouseKey);
            });
          },
          onCancel() {},
        });
      }
    },
    async handleOk() {
      this.rightFlag = true;
      if (!this.leftFlag) {
        if (this.treeData.length >= 1) {
          this.treeData.forEach((item) => {
            if (item.titleName === this.titleName) {
              this.rightFlag = false;
            }
          });
        } else {
          this.rightFlag = true;
        }
      } else {
        if (this.CheckData.length >= 1) {
          this.CheckData.forEach((item) => {
            if (item.titleName === this.titleName) {
              this.rightFlag = false;
            }
          });
        } else {
          this.rightFlag = true;
        }
      }

      if (this.rightFlag) {
        if (this.titleName != "") {
          let { code } = await warehouse_add({
            titleName: this.titleName,
            warehousePName: this.warehousePName,
            warehousePid: this.threeDataisEditKey
              ? this.threeDataisEditKey
              : this.warehouseKey,
            sortNo: this.sortNo * 1,
          });
          if (code === "10000") {
            if (this.addOneFlag) {
              this.getWarehouseTree(this.warehouseKey);
              this.addOneFlag = false;
            } else {
              this.getWarehouseTree(this.warehouseKey);
            }
            this.titleName = null;
            this.threeDataisEditKey = null;
            this.sortNo = null;
            this.visible = false;
          }
        } else {
          this.$message.error("仓库名不能为空！");
          return false;
        }
      } else {
        this.$message.error("同级目录不能重复区域名！");
      }
    },
    //添加一级仓库
    addOneTree() {
      this.addOneFlag = true;
      this.threeDataisEditKey = null;
      this.modalTitle = "添加一级库位";
      this.visible = true;
      this.leftFlag = false;
    },
    //查询仓库
    searchWarehouse(item) {
      this.addOneFlag = true;
      this.warehouseKey = item.warehouseId;
      this.getWarehouseTree(this.warehouseKey);
      this.cardTitle = item.titleName;
    },
    //获取仓库树
    async getWarehouseTree(key = 1) {
      this.spinning = true;
      let { code, responseBody } = await warehouse_select({
        warehousePid: key,
        isTree: true,
      });
      if (code === "200") {
        this.treeData = JSON.stringify(this.getSkuTypeThree(responseBody));
        this.treeData = JSON.parse(this.treeData);

        if (this.addOneFlag) {
          this.rightData = [...this.treeData];
        }
        if (this.link && !this.addOneFlag) {
          this.link.click();
        }
        this.generateList(this.treeData);
        this.spinning = false;
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //搜索框搜索
    onChange(e) {
      const value = e.target.value;
      const expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.title, this.treeData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    getParentKey(title, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some((item) => item.title === title)) {
            parentKey = node.title;
          } else if (this.getParentKey(title, node.children)) {
            parentKey = this.getParentKey(title, node.children);
          }
        }
      }
      return parentKey;
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.title;
        this.dataList.push({ key, title: node.title });
        if (node.children) {
          this.generateList(node.children);
        }
      }
    },
    //获取仓库列表
    async getWarehouseList() {
      let { code, responseBody } = await warehouse({
        warehousePid: 0,
      });
      if (code === "200") {
        this.warehouseData = responseBody;

        this.cardTitle = this.warehouseData[0].titleName;
        this.warehouseKey = this.warehouseData[0].warehouseId;
      }
    },
    //封装组装后台数据
    getSkuTypeThree(data) {
      data.forEach((item) => {
        item.scopedSlots = { title: "title" };
        item.isEdit = false;
        item.title = item.titleName;
        item.isDisable == "0"
          ? // item.num=num++
            (item.isDisable = false)
          : (item.isDisable = true);
        item.children = item.child;
        item.sort = this.sort;
        if (item.children && item.children.length >= 1) {
          this.sort += 1;
          this.getSkuTypeThree(item.children);
        }
      });
      this.sort = 0;
      return data;
    },
  },
};
</script>

<style lang="less" scoped>
.topBtn {
  span {
    margin: 0 10px;
  }
}
.content {
  margin: 10px;
  display: flex;
  .left-tree {
    text-align: center;
    border: 1px solid #e8e8e8;
    width: 100%;
    .tree {
      font-size: 18px;
      width: 250px;
      display: flex;
      justify-content: space-between;
    }
  }
  div:nth-child(2) {
    width: 70%;
  }
  div {
    padding: 20px;
  }
}
</style>
